<template>
  <div class="search-suggestion">
    <van-cell
      icon="search"
      v-for="(text, index) in suggestions"
      :key="index"
      @click="$emit('search', text)"
    >
      <span slot="title" v-html="highLight(text)"></span>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  components: {},
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      suggestions: []
    }
  },
  computed: {},
  watch: {
    searchText: {
      handler: debounce(function(val) {
        this.loadSearchSuggestion(val)
      }, 300),
      immediate: true
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 联想词函数
    async loadSearchSuggestion(val) {
      try {
        const { data } = await getSearchSuggestions(val)
        // console.log('联想词', data)
        this.suggestions = data.data.options
      } catch (error) {
        this.$toast('获取数据失败，请稍后重试！')
      }
    },
    highLight(text) {
      const highLightStr = `<span class="active">${this.searchText}</span>`
      //   动态创建正则表达式，手动 new RegExp（）
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highLightStr)
    }
  }
}
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/ span.active {
    color: #2892ff;
  }
}
</style>
